<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;

class Book extends Controller
{
    public function __construct()
    {
        parent::__construct();
        if(!session('name')){
            $this->redirect("/admin/login/login");
        }
    }
    public function index(){
        $bookList=Db::name('book')->select();
        $this->assign('bookList',$bookList);
        return $this->fetch();
    }
    public function add(){
        if(request()->isPost()){
            $data=input('param.');
            $checkData=new \app\admin\Validate\Book();
            if(!$checkData->check($data)){
                return $this->error($checkData->getError());
            }
            $data['book_creat_time']=time();
            $book=(new \app\common\model\Book());
            $checkName=$book->checkName($data);
            if(!$checkName){
                return $this->error("图书名称已存在，请更换名称");
            }else{
                $res=$book->allowField(true)->save($data);
                if($res){
                    return $this->success('图书添加成功');
                }else{
                    return $this->error("图书添加失败");
                }
            }
        }
        return $this->fetch();
    }
    public function delete(){
        $bookId=input('param.id');
        $res=Db::name('book')->where('book_id',$bookId)->delete();
        if($res){
            return $this->success("删除成功");
        }else{
            return $this->error("删除失败");
        }

    }
}
